package com.karina.visualization.chart.skins;

import java.util.List;

import com.karina.visualization.chart.client.Graphics;
import com.karina.visualization.chart.model.XAxisModel;

public class XAxisSkin extends BaseSkin<XAxisModel> {

	private XAxisModel data;

	@Override
	public void setData(XAxisModel data) {
		this.data = data;
	}

	@Override
	public XAxisModel getData() {
		return data;
	}

	@Override
	public void draw(Graphics graphics) {
		drawLine(graphics);
		drawCategoryPoint(graphics);
	}

	private void drawCategoryPoint(Graphics graphics) {
		int y = (int) (data.getY() + data.getHeight() - data.getTextMargin());
		int width = (int) (data.getWidth() - data.getTextMargin());

		List<String> categories = getData().getCategories();

		int markNum = categories.size();

		graphics.saveContext();
		setStyle(graphics);
		double gap = width / markNum;

		double prepoint = 0;

		double markPoint = gap + getData().getX() + data.getTextMargin();

		if (data.isStartFromZeroPoint()) {
			markPoint -= gap;
			gap = width / (markNum - 1);
		}

		graphics.beginPath();

		for (String category : categories) {
			graphics.moveTo(markPoint, y - 5)
					.lineTo(markPoint, y);
			if(data.isStartFromZeroPoint()){
					graphics.drawText(markPoint, y + 5, category,
							"right", "top");
			}else{
				graphics.drawText((prepoint + markPoint) /2 , y + 5, category,
						"center", "top");
			}

			prepoint = markPoint;
			markPoint += gap;
		}
		graphics.stroke();
		graphics.endPath();
		graphics.restoreContext();
	}

	private void drawLine(Graphics graphics) {
		int height = (int) (data.getHeight() - data.getTextMargin());
		int x = (int) (data.getX() + data.getTextMargin());
		int y = data.getY();
		int width = (int) (data.getWidth() - data.getTextMargin());

		graphics.saveContext();

		setStyle(graphics);

		graphics.beginPath();

		graphics.moveTo(x, y + height);
		graphics.lineTo(x + width, y + height);
		graphics.stroke();
		graphics.endPath();
		graphics.restoreContext();
	}

	@Override
	public void cleanup(Graphics graphics) {
		// TODO Auto-generated method stub

	}

	@Override
	public void refresh(Graphics graphics) {
		// TODO Auto-generated method stub

	}

}
